package reflection.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class reflectionTest1 {
	public static void main(String[] args) throws Exception {

		Class c4 = Class.forName("reflection.Test.Person");
		System.out.println("class name is: " + c4);

		Class superc4 = c4.getSuperclass();
		System.out.println("super class is: " + superc4);

		printConstructors(c4);

		printMethods(c4);
		
		printFields(c4);

		//调用无参数函数
		Constructor co = c4.getConstructor(null);
		Object obj = co.newInstance(null);
		Method m = c4.getMethod("show", null);
		m.invoke(obj, null);
		
		//调用有参数构造函数
		Method showdetail = c4.getMethod("showdetail", new Class[] {int.class,String.class});
		 //获得参数Object
	    Object[] arguments = new Object[]{new Integer(23),new String("abc")};
	    showdetail.invoke(obj, arguments);

	}

	/**
	 * Prints all constructors of a class
	 * 
	 * @param cl
	 *            a class
	 */
	public static void printConstructors(Class cl) {
		System.out.println("printConstructors");
		Constructor[] constructors = cl.getDeclaredConstructors();

		for (Constructor c : constructors) {
			String name = c.getName();
			System.out.print("   " + Modifier.toString(c.getModifiers()));
			System.out.print(" " + name + "(");

			// print parameter types
			Class[] paramTypes = c.getParameterTypes();
			for (int j = 0; j < paramTypes.length; j++) {
				if (j > 0)
					System.out.print(", ");
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}
	}

	/**
	 * Prints all methods of a class
	 * 
	 * @param cl
	 *            a class
	 */
	public static void printMethods(Class cl) {
		System.out.println("printMethods");
		Method[] methods = cl.getDeclaredMethods();

		for (Method m : methods) {
			Class retType = m.getReturnType();
			String name = m.getName();

			// print modifiers, return type and method name
			System.out.print("   " + Modifier.toString(m.getModifiers()));
			System.out.print(" " + retType.getName() + " " + name + "(");

			// print parameter types
			Class[] paramTypes = m.getParameterTypes();
			for (int j = 0; j < paramTypes.length; j++) {
				if (j > 0)
					System.out.print(", ");
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}
	}

	/**
	 * Prints all fields of a class
	 * 
	 * @param cl
	 *            a class
	 */
	public static void printFields(Class cl) {
		System.out.println("printFields");
		Field[] fields = cl.getDeclaredFields();

		for (Field f : fields) {
			Class type = f.getType();
			String name = f.getName();
			System.out.print("   " + Modifier.toString(f.getModifiers()));
			System.out.println(" " + type.getName() + " " + name + ";");
		}
	}

}
